<template>
  <div class="index">
    <div class="dashboardAuth">
      <MyPlanHeader :formData="planInfo" @submitFn="submit" @cancelFn="cancel"></MyPlanHeader>
    </div>
    <div>
      <form class="layui-form con item">
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>计划包名称</label>
          <div class="layui-inline">
            <input type="text" v-model="planInfo.name" class="layui-input updata" placeholder="请输入计划包名称，建议长度不超过30字" lay-verify="required">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">计划包简介</label>
          <div class="layui-input-block">
            <textarea class="layui-textarea abstract" maxlength="300" name="intro" v-model="planInfo.intro" text placeholder="请输入"></textarea>
            <div class="abstract-num">
              <span num>{{planInfo.intro.length}}</span>
              <i>/</i>
              <span>300</span>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">能力圈</label>
          <div class="layui-input-block">
            <textarea class="layui-textarea abstract" name="abilityCircle" v-model="planInfo.abilityCircle" maxlength="300" text placeholder="请输入"></textarea>
            <div class="abstract-num">
              <span num>{{planInfo.abilityCircle.length}}</span>
              <i>/</i>
              <span>300</span>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">更新频率</label>
          <div class="layui-inline">
            <input type="text" class="layui-input updata" name="updateFrequency" v-model="planInfo.updateFrequency" placeholder="请输入">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>期限</label>
          <div class="layui-inline">
            <template v-if="id">
              <select name="timeLimit" v-model="planInfo.timeLimit" disabled>
                <option value="月">月</option>
                <option value="季度">季度</option>
                <option value="半年">半年</option>
                <option value="年">年</option>
              </select>
            </template>
            <template v-else>
              <select name="timeLimit" v-model="planInfo.timeLimit">
                <option value="月">月</option>
                <option value="季度">季度</option>
                <option value="半年">半年</option>
                <option value="年">年</option>
              </select>
            </template>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>开始时间</label>
          <div class="layui-inline">
            <input type="text" class="layui-input" id="beginTime" name="beginTime" :disabled="id">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>结束时间</label>
          <div class="layui-inline">
            <input type="text" class="layui-input" id="endTime" name="endTime" :disabled="id">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>价格</label>
          <div class="layui-inline">
            <input type="number" class="layui-input" step="1" placeholder="请输入价格" name="price" v-model="planInfo.price" :disabled="id">
          </div>
          <span>中亿币</span>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            <i class="must">*</i>是否停售</label>
          <div class="layui-inline">
            <select name="saleFlag" v-model="planInfo.saleFlag">
              <option value="1">否</option>
              <option value="0">是</option>
            </select>
          </div>
        </div>
      </form>
    </div>
    <Footer/>
  </div>
</template>

<script>
import Footer from '@/components/footer'
import MyPlanHeader from '@/components/plan/new-plan-article-header'
import { addPlan, updatePlanSimpleInfo, getPlanSimpleInfo } from '@/service/api'
import { parseTimeToStamp } from '@/utils/assist'
let $ = window.$
export default {
  components: {
    Footer,
    MyPlanHeader
  },
  data () {
    return {
      id: '',
      planInfo: {
        name: '',
        intro: '',
        abilityCircle: '',
        updateFrequency: '',
        timeLimit: '',
        beginTime: '',
        endTime: '',
        price: '',
        saleFlag: ''
      },
      layerLoad: null,
      submitting: false // 正在提交
    }
  },
  created () {
  },
  mounted () {
    this.$nextTick(() => {
      this.id = this.$route.params.id
      if (!this.id) {
        this.initLayui()
      } else {
        this.getPlan()
      }
    })
  },
  methods: {
    showLoadingModal () {
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
    },
    closeLoadingModal () {
      if (window.layer) {
        window.layer.close(this.layerLoad)
      }
    },
    initLayui () {
      window.layui.use(['form', 'laydate'], () => {
        var form = window.layui.form
        form.on('select', (data) => {
          this.$set(this.planInfo, $(data.elem).attr('name'), data.value)
        })
        form.render()
        // 日期插件
        var laydate = window.layui.laydate
        let valPicker1 = {
          value: new Date(this.planInfo.beginTime)
        }
        if (this.planInfo.beginTime === '') {
          valPicker1 = {}
        }
        laydate.render({
          ...valPicker1,
          elem: '#beginTime',
          type: 'datetime',
          isInitValue: this.planInfo.beginTime !== '', // 是否允许填充初始值，默认为 true
          done: (value, date, endDate) => {
            this.planInfo.beginTime = parseTimeToStamp(value)
          }
        })
        let valPicker2 = {
          value: new Date(this.planInfo.endTime)
        }
        if (this.planInfo.endTime === '') {
          valPicker2 = {}
        }
        laydate.render({
          ...valPicker2,
          elem: '#endTime',
          type: 'datetime',
          isInitValue: this.planInfo.endTime !== '', // 是否允许填充初始值，默认为 true
          done: (value, date, endDate) => {
            this.planInfo.endTime = parseTimeToStamp(value)
          }
        })
      })
    },
    cancel () {
      this.$router.go(-1)
    },
    submit () {
      window.layui.use(['layer'], () => {
        if (this.validate()) {
          if (!this.id) {
            this.addNewPlan()
          } else {
            this.updatePlan()
          }
        }
      })
    },
    async addNewPlan () {
      // if (this.submitting) {
      //   this.showMsgTip('内容提交中……')
      //   return false
      // }
      this.submitting = true
      this.showLoadingModal()
      try {
        let res = await addPlan({ ...this.planInfo })
        if (res.status && res.data.code === 200) {
          this.closeLoadingModal()
          this.showMsgTip('添加成功')
          setTimeout(() => {
            this.$router.go(-1)
          }, 500)
        } else {
          this.submitting = false
          this.showMsgTip('添加失败，请重试')
        }
      } catch (e) {
        if (window.layer) {
          window.layer.closeAll()
        }
      }
    },
    validate () {
      if (!(this.planInfo.name && /^.{1,30}$/.test(this.planInfo.name))) {
        this.showMsgTip('请输入1-30位字符的计划包名称')
        return false
      }
      if (!this.planInfo.intro && this.planInfo.intro.length > 300) {
        this.showMsgTip('计划包内容超长，最多300个字符')
        return false
      }
      if (!this.planInfo.abilityCircle && this.planInfo.abilityCircle.length > 300) {
        this.showMsgTip('能力圈内容超长，最多300个字符')
        return false
      }
      if (!(this.planInfo.timeLimit)) {
        this.showMsgTip('请选择期限')
        return false
      }
      if (!(this.planInfo.beginTime)) {
        this.showMsgTip('请选择开始时间')
        return false
      }
      if (!(this.planInfo.endTime)) {
        this.showMsgTip('请选择结束时间')
        return false
      }
      if (this.planInfo.endTime <= this.planInfo.beginTime) {
        this.showMsgTip('开始时间不能晚于结束时间')
        return false
      }
      if (!/^[0-9]*[1-9][0-9]*$/.test(this.planInfo.price)) {
        this.showMsgTip('价格必须是1-99999的整数')
        return false
      }
      if (!(this.planInfo.saleFlag)) {
        this.showMsgTip('请选择是否停售')
        return false
      }
      return true
    },
    async getPlan () {
      this.submitting = true
      this.showLoadingModal()
      try {
        let res = await getPlanSimpleInfo({ planId: this.id })
        this.closeLoadingModal()
        let data = res.data
        let tempData = {}
        if (data && data.code === 200) {
          for (let item in this.planInfo) {
            tempData[item] = data.data[item]
          }
          tempData.planId = data.data.planId
        } else {
          this.showMsgTip('数据加载失败，请重试')
        }
        this.planInfo = tempData
        this.submitting = false
        this.initLayui()
        setTimeout(() => {
          window.layui.form.render()
        }, 500)
      } catch (e) {
        this.submitting = false
      }
    },
    async updatePlan () {
      if (this.submitting) {
        this.showMsgTip('内容提交中……')
        return
      }
      this.submitting = true
      this.showLoadingModal()
      // 不能更新的字段 开始时间、结束时间、价格、期限字段 'timeLimit', 'beginTime', 'endTime', 'price'
      let tempInfo = { ...this.planInfo }
      delete tempInfo.timeLimit
      delete tempInfo.beginTime
      delete tempInfo.endTime
      delete tempInfo.price
      let res = await updatePlanSimpleInfo(tempInfo)
      this.closeLoadingModal()
      if (res.status && res.data.code === 200) {
        this.showMsgTip('更新成功')
        setTimeout(() => {
          this.$router.go(-1)
        }, 500)
      } else {
        this.submitting = false
        this.showMsgTip('更新失败，' + res.data.message)
      }
    },
    showMsgTip (msg) {
      window.layui.layer.msg(msg)
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../style/res/viewpoint";
.layui-input-block {
  margin-left: 135px;
}
.must {
  color: red;
  padding-right: 5px;
}
.con .abstract {
  resize: none;
  width: 430px;
  padding: 10px 16px;
  text-align: left;
}
.con .layui-input-block {
  position: relative;
}
.con .abstract-num {
  position: absolute;
  right: 355px;
  bottom: 6px;
  color: #808080;
}
.con .layui-inline .updata {
  text-align: left;
  padding: 0 16px;
  width: 360px;
}
.con .layui-inline span {
  line-height: 42px;
}
.layui-inline {
  padding-left: 5px;
}
</style>
